package com.dyj.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.dyj.common.client.AuthClient;
import com.dyj.common.config.AgentConfiguration;
import com.dyj.common.domain.query.BaseQuery;
import com.dyj.common.domain.vo.TpV2AuthTokenVo;
import com.dyj.common.utils.DyConfigUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author danmo
 * @date 2024-06-26 17:04
 **/
@Component
public class TpV2AuthTokenHeaderInterceptor implements Interceptor<Object> {

    private final Log log = LogFactory.getLog(TpV2AuthTokenHeaderInterceptor.class);

    @Resource
    private AuthClient authClient;

    @Override
    public boolean beforeExecute(ForestRequest request) {
        Integer tenantId = null;
        String clientKey = "";
        Object[] arguments = request.getArguments();
        for (Object argument : arguments) {
            if (argument instanceof BaseQuery) {
                BaseQuery query = (BaseQuery) argument;
                tenantId = query.getTenantId();
                clientKey = query.getClientKey();
            }
        }

        TpV2AuthTokenVo tpV2AuthToken = DyConfigUtils.getAgentTokenService().getTpV2AuthToken(tenantId, clientKey);
        if (Objects.isNull(tpV2AuthToken)) {
            AgentConfiguration agent = DyConfigUtils.getAgent(tenantId, clientKey);
            BaseQuery query = new BaseQuery();
            query.setTenantId(tenantId);
            query.setClientKey(clientKey);
            tpV2AuthToken = authClient.tpV2AuthToken(query, "app_to_tp_authorization_code", agent.getAuthorization_code(), null).getData();
            if (Objects.nonNull(tpV2AuthToken) && StringUtils.hasLength(tpV2AuthToken.getAuthorizer_access_token())) {
                DyConfigUtils.getAgentTokenService().setTpV2AuthToken(tenantId, clientKey, tpV2AuthToken);
            }
        }

        if (Objects.isNull(tpV2AuthToken)) {
            throw new RuntimeException("authorizer_access_token is null");
        }
        request.addHeader("access-token", tpV2AuthToken.getAuthorizer_access_token());
        return Interceptor.super.beforeExecute(request);
    }

    @Override
    public void onError(ForestRuntimeException ex, ForestRequest request, ForestResponse response) {
        StringBuilder sb = new StringBuilder("TpThirdV2TokenHeaderInterceptor onError ");
        sb.append("url:");
        sb.append(request.getUrl());
        sb.append(", ");
        sb.append("params:");
        sb.append(JSONObject.toJSONString(request.getArguments()));
        sb.append(", ");
        sb.append("result:");
        sb.append(response.getContent());
        sb.append(", ");
        sb.append("msg:");
        sb.append(ex.getMessage());
        log.info(sb.toString());
    }
}
